package com.buddies.lottery.base;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.observers.DisposableObserver;
import io.reactivex.schedulers.Schedulers;


/**
 * Description: Presenter 基类
 * Date: 2018/2/11
 * Author: xuliang
 */
public class BasePresenter<V extends IView> implements IPresenter<V> {

    private CompositeDisposable mCompositeDisposable;
    protected V mView;

    private BasePresenter() {
    }

    public BasePresenter(V view) {
        this();
        attachView(view);
    }

    @Override
    public void attachView(V view) {
        this.mView = view;
    }

    @Override
    public void detachView() {
        onUnSubscribe();
    }

    public <T> void addSubscription(Observable<T> observable, DisposableObserver<T> observer) {
        if (mCompositeDisposable == null) {
            mCompositeDisposable = new CompositeDisposable();
        }
        DisposableObserver<T> disposableObserver = observable
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .unsubscribeOn(AndroidSchedulers.mainThread())
                .subscribeWith(observer);
        mCompositeDisposable.add(disposableObserver);
    }

    public <T> void addComputationSubscription(Observable<T> observable, DisposableObserver<T> observer) {
        if (mCompositeDisposable == null) {
            mCompositeDisposable = new CompositeDisposable();
        }
        DisposableObserver<T> disposableObserver = observable
                .subscribeOn(Schedulers.computation())
                .observeOn(AndroidSchedulers.mainThread())
                .unsubscribeOn(AndroidSchedulers.mainThread())
                .subscribeWith(observer);
        mCompositeDisposable.add(disposableObserver);
    }

    /**
     * rxJava取消注册，以避免内存泄露
     */
    protected void onUnSubscribe() {
        if (mCompositeDisposable != null && !mCompositeDisposable.isDisposed()) {
            mCompositeDisposable.dispose();
        }
    }
}
